<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://www.lzcit.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: lzc <1094214985@qq.com>
// +----------------------------------------------------------------------

// [ 微信公众平台 ]

class Wechat{

	public function __construct(){

	}

	public function checkAuth()
	{
		$wechat = $_GET["wechat"];
		$signature = $_GET["signature"];
		$echostr = $_GET["echostr"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
		$wechat = $this->getWechat($wechat);
		$token = $wechat["token"];
		$array = [$token,$timestamp,$nonce];
		sort($array);
		$sign = sha1(implode('', $array));
		if ($sign == $signature) {
			echo $echostr;
		}
		exit();
	}

	public function getWechat($id)
	{
		return db("wechat_site")->where("id = ".$id)->find();
	}

	public function getAccessToken($id)
	{
		$file = config("afs.document_root")."/cache/token/wechat".$id.".txt";
		$token = is_file($file) ? file_get_contents($file) :true;
		$tokenArr = json_decode($token,true);
		if (!isset($tokenArr["access_token"]) || $tokenArr["time"] < (time() - 7200)) {
			$wechat = $this->getWechat($id);
			$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$wechat["appid"].'&secret='.$wechat["appsecret"];
			$jsonStr = curl($url);
	        $tokenArr = json_decode($jsonStr,true);
	        $tokenArr["time"] = time();
	        file_put_contents($file,json_encode($tokenArr));
		}
		$access_token = $tokenArr["access_token"];
		return $access_token;
	}

	public function mkNav($id,$data)
	{
		$access_token = $this->getAccessToken($id);
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
		$back = postCurl($url,$data);
		return $back;
	}

}


